﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZFine.Domain.Entity.Gas;
using ZFine.Domain.Entity.SystemManage;
using ZFine.Application.SystemManage;
using ZFine.Application.Gas;

using ZFine.Code;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace ZFine.Web.Areas.Gas.Controllers
{
    public class APPController : Controller
    {
        private ChargeRecordApp chargeRecordApp = new ChargeRecordApp();
        private DispenserApp dispenserApp = new DispenserApp();
        private CompanyApp companyApp = new CompanyApp();
        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();
        private BottleApp bottleApp = new BottleApp();
        private ResidentApp residentApp = new ResidentApp();
        private FaceRecordApp faceRecordApp = new FaceRecordApp();
        private DiningRecordApp diningRecordApp = new DiningRecordApp();
        private FaceRecordLogApp faceRecordLogApp = new FaceRecordLogApp();
        /// <summary>
        /// 测试12
        /// </summary>
        [HttpGet]
        public ActionResult GetTest(string timestamp, string sign)
        {
            if (DESEncrypt.EncryptMD5(timestamp) == sign.ToUpper())
            {
                APP_ReturnListString r = new APP_ReturnListString()
                {
                    errcode = 0,
                    errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(),
                    data = ZFine.Code.EnumHelper.GetEnumListStringValues(typeof(ZFine.Application.Enum.Gas.FaceRecordSatisfaction))
                };
                return Content(r.ToJson());
            }
            return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
        }
        /// <summary>
        /// 1.0 测试
        /// </summary>
        [HttpPost]
        public ActionResult FaceTest(Face fa)
        {

            var sr = new StreamReader(Request.InputStream);
            string stream = sr.ReadToEnd();
            return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
        }
        /// <summary>
        /// 1.1 注册 Post提交 参数timestamp sign RName IDNumber PhotoBase64
        /// </summary>
        [HttpPost]
        public ActionResult FaceReg(Face fa)
        {
            string timespan = fa.timestamp;
            string sign = fa.sign;
            string rname = fa.RName;
            string idnumber = fa.IDNumber;
            string photo = fa.PhotoBase64;
            string address = fa.address;
            string telephone = fa.telephone;

            if (ZFine.Code.DEncrypt.EncryptMD5(timespan) == sign.ToUpper())
            {
                Code.IDCardValidation c = new IDCardValidation(idnumber);
                if (!c.IsValidation)
                {
                    return Content((new APP_ReturnMessage() { errcode = 11, errmsg = ZFine.Application.Enum.Gas.errmsg.身份证号输入有误.ToString() }).ToJson());
                }
                if (c.NL<70)
                {
                    return Content((new APP_ReturnMessage() { errcode = 12, errmsg = ZFine.Application.Enum.Gas.errmsg.年龄不足70岁.ToString() }).ToJson());
                }
                if (residentApp.GetIQueryable(idnumber).Count() > 0)
                {
                    return Content((new APP_ReturnMessage() { errcode = 6, errmsg = ZFine.Application.Enum.Gas.errmsg.该身份证号已经注册.ToString() }).ToJson());
                }
                string filename = "";
                if (photo.Length > 0)
                {
                    byte[] arr = Convert.FromBase64String(photo);
                    string dir = string.Format("{0}/{1}", PubClass.faceRegPath, idnumber);
                    string dirServer = Server.MapPath(string.Format("~/{0}", dir));
                    if (!Directory.Exists(dirServer))
                    {
                        Directory.CreateDirectory(dirServer);
                    }
                    filename = string.Format("{0}/{1}.jpg", dir, idnumber);
                    string filenameServer = Server.MapPath(string.Format("~/{0}", filename));
                    System.IO.File.WriteAllBytes(filenameServer, arr);
                }
                else
                {
                    return Content((new APP_ReturnMessage() { errcode = 7, errmsg = ZFine.Application.Enum.Gas.errmsg.无照片信息.ToString() }).ToJson());
                }
                ResidentEntity resident = new ResidentEntity()
                {
                    RName = rname,
                    IDNumber = idnumber,
                    FaceRecognize = true,
                    FaceRecognizeTime = DateTime.Now,
                    FaceData = filename,
                    CanteenId = "",
                    telephone = telephone,
                    address = address
                };
                residentApp.ClientInsert(resident);
                return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
            }
            return Content((new APP_ReturnMessage() { errcode = 1, errmsg = ZFine.Application.Enum.Gas.errmsg.登陆失败.ToString() }).ToJson());
        }
        /// <summary>
        /// 1.2 面部识别成功 Post提交 提交人员和满意度 参数timestamp sign IDNumber Satisfaction 满意度 PhotoBase64 
        /// </summary>
        [HttpPost]
        public ActionResult FaceSubmit(Face fa)
        {
            string timespan = fa.timestamp;
            string sign = fa.sign;
            string idnumber = fa.IDNumber;
            string photo = fa.PhotoBase64;
            string satisfaction = fa.Satisfaction;

            if (ZFine.Code.DEncrypt.EncryptMD5(timespan) == sign.ToUpper())
            {
                ResidentEntity resident = residentApp.GetIQueryable(idnumber).FirstOrDefault();
                //先检查是否已经采集
                if (resident == null)
                {
                    return Content((new APP_ReturnMessage() { errcode = 101, errmsg = "该居民不存在" }).ToJson());
                }
                if (!resident.FaceRecognize)
                {
                    return Content((new APP_ReturnMessage() { errcode = 101, errmsg = "面部数据尚未采集，请先采集" }).ToJson());
                }
                string filename = "";
                if (photo.Length > 0)
                {
                    byte[] arr = Convert.FromBase64String(photo);
                    string dir = string.Format("{0}/{1}", PubClass.faceRegPath, idnumber);
                    string dirServer = Server.MapPath(string.Format("~/{0}", dir));
                    if (!Directory.Exists(dirServer))
                    {
                        Directory.CreateDirectory(dirServer);
                    }
                    filename = string.Format("{0}/{1}.jpg", dir, DateTime.Now.ToString(PubClass.TimeFormat2));
                    string filenameServer = Server.MapPath(string.Format("~/{0}", filename));
                    System.IO.File.WriteAllBytes(filenameServer, arr);
                }
                else
                {
                    return Content((new APP_ReturnMessage() { errcode = 7, errmsg = ZFine.Application.Enum.Gas.errmsg.无照片信息.ToString() }).ToJson());
                    
                }
                //插入原始数据
                FaceRecordLogEntity faceRecordRawEntity = new FaceRecordLogEntity()
                {
                    IDNumber = idnumber,
                    PhotoString = photo,
                    Satisfaction = satisfaction
                };
                faceRecordLogApp.ClientInsert(faceRecordRawEntity);
                //插入当天记录，看这个身份证号，当天有没有记录
                FaceRecordEntity f = faceRecordApp.GetList(idnumber, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).OrderByDescending(a => a.FaceData).FirstOrDefault();
                if (f!=null)
                {
                    //有记录，修改这条记录的数据
                    f.ResidentId = resident.F_Id;
                    f.RName = resident.RName;
                    f.RecordTime = DateTime.Now;
                    f.FaceData = filename;
                    f.Satisfaction = satisfaction;
                    f.Result = Application.Enum.Gas.FaceRecordResult.未刷卡.ToString();
                    faceRecordApp.ClientUpdate(f);
                }
                else
                {
                    //没有记录则新增
                    FaceRecordEntity faceRecord = new FaceRecordEntity()
                    {
                        ResidentId = resident.F_Id,
                        RName = resident.RName,
                        IDNumber = resident.IDNumber,
                        Year = DateTime.Now.Year,
                        Month = DateTime.Now.Month,
                        Day = DateTime.Now.Day,
                        RecordTime = DateTime.Now,
                        FaceData = filename,
                        Satisfaction = satisfaction,
                        Result = Application.Enum.Gas.FaceRecordResult.未刷卡.ToString(),
                        DiningRecordId = ""
                    };
                    faceRecordApp.ClientInsert(faceRecord);
                }
                
                return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
            }
            return Content((new APP_ReturnMessage() { errcode = 1, errmsg = ZFine.Application.Enum.Gas.errmsg.登陆失败.ToString() }).ToJson());
        }
        /// <summary>
        /// 1.3 满意度选项
        /// </summary>
        [HttpGet]
        public ActionResult GetSatisfactionList(string timestamp, string sign)
        {
            if (DESEncrypt.EncryptMD5(timestamp) == sign.ToUpper())
            {
                APP_ReturnListString r = new APP_ReturnListString()
                {
                    errcode = 0,
                    errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(),
                    data = ZFine.Code.EnumHelper.GetEnumListStringValues(typeof(ZFine.Application.Enum.Gas.FaceRecordSatisfaction))
                };
                return Content(r.ToJson());
            }
            return Content((new APP_CompanyArea_Return()
            {
                errcode = 1,
                errmsg = ZFine.Application.Enum.Gas.errmsg.验证失败.ToString(),
                data = null
            }).ToJson());
        }
        /// <summary>
        /// 1.4 删除居民数据 在APP端同时删除面部识别信息
        /// </summary>
        [HttpGet]
        public ActionResult DeleteResident(string timestamp, string sign, string IDNumber)
        {
            if (DESEncrypt.EncryptMD5(timestamp) == sign.ToUpper())
            {
                ResidentEntity resident = residentApp.GetList(IDNumber).FirstOrDefault();
                if (resident == null)
                {
                    return Content((new APP_ReturnMessage() { errcode = 8, errmsg = ZFine.Application.Enum.Gas.errmsg.该身份证不存在.ToString() }).ToJson());
                }
                residentApp.Del(resident.F_Id);
                return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
            }
            return Content((new APP_ReturnMessage() { errcode = 1, errmsg = ZFine.Application.Enum.Gas.errmsg.登陆失败.ToString() }).ToJson());
        }
        /// <summary>
        /// 2.1 客户端食堂上传消费记录
        /// </summary>
        [HttpPost]
        public ActionResult ClientUpload(string timestamp, string sign, string clientdata)
        {
            if (DESEncrypt.EncryptMD5(timestamp) == sign.ToUpper())
            {
                List<DiningRecordClient> l_client = JsonConvert.DeserializeObject<List<DiningRecordClient>>(clientdata);
                List<DiningRecordEntity> l = new List<DiningRecordEntity>();
                if (l_client == null)
                {
                    return Content((new APP_ReturnMessage() { errcode = 10, errmsg = ZFine.Application.Enum.Gas.errmsg.上传数据格式错误.ToString() }).ToJson());
                }
                foreach (DiningRecordClient c in l_client)
                {
                    DiningRecordEntity d = new DiningRecordEntity()
                    {
                        CanteenId = "",
                        RName = c.name,
                        IDNumber = c.note,
                        Year = c.recdate.Year,
                        Month = c.recdate.Month,
                        Day = c.recdate.Day,
                        DiningTime = c.rectime,
                        DiningSpan = "",
                        Amount = c.price
                    };
                    l.Add(d);
                    //比对当天刷脸匹配数据，每天刷脸数据只有一条
                    FaceRecordEntity f = faceRecordApp.GetList(d.IDNumber, d.Year, d.Month, d.Day).OrderByDescending(a=>a.FaceData).FirstOrDefault();
                    if (f!=null)
                    {
                        f.Result = ZFine.Application.Enum.Gas.FaceRecordResult.已刷卡.ToString();
                        faceRecordApp.ClientUpdate(f);
                    }
                }
                diningRecordApp.ClientInsert(l);
                return Content((new APP_ReturnMessage() { errcode = 0, errmsg = ZFine.Application.Enum.Gas.errmsg.成功.ToString(), records = 0 }).ToJson());
            }
            return Content((new APP_ReturnMessage() { errcode = 1, errmsg = ZFine.Application.Enum.Gas.errmsg.登陆失败.ToString() }).ToJson());
        }
    }

    public class Face
    {
        public string IDNumber { get; set; }
        public string PhotoBase64 { get; set; }
        public string RName { get; set; }
        public string sign { get; set; }
        public string timestamp { get; set; }
        public string Satisfaction { get; set; }
        public string telephone { get; set; }
        public string address { get; set; }
    }
    public class DiningRecordClient
    {
        public string cardid
        {
            get;
            set;
        }
        public string workno
        {
            get;
            set;
        }
        public DateTime rectime
        {
            get;
            set;
        }
        public DateTime recdate
        {
            get;
            set;
        }
        public int macid
        {
            get;
            set;
        }
        public int rectypeid
        {
            get;
            set;
        }
        public float price
        {
            get;
            set;
        }
        public string name
        {
            get;
            set;
        }
        public string username//这是读卡记录中的姓名
        {
            get;
            set;
        }
        public string note//备注，也就是身份证号
        {
            get;
            set;
        }

    }
}

